package com.hs.telepass.ui;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;
import com.hs.teleform.R;
import com.hs.telepass.Constants;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.controller.task.SendAuthTask;
import com.hs.telepass.controller.task.UpdateSessionTask;
import com.hs.telepass.manager.ProfilesManager;
import com.hs.telepass.manager.SingouManager;
import com.hs.telepass.manager.TeleformManager;
import com.hs.telepass.model.Profile;
import com.hs.telepass.model.QrCodeModal;
import com.hs.telepass.model.RepositoryProfile;
import com.hs.telepass.ui.Adapter.MultiLoginUserAdapter;
import com.hs.telepass.utils.ShortSoundUtil;
import com.hs.telepass.utils.ToastUtil;

import java.util.List;

public class MultiUserInfoActivity extends BaseActivity {


    @InjectView(R.id.btn_cancel)
    Button mBtnCancel;
    @InjectView(R.id.user_list)
    ListView mUserList;
    @InjectView(R.id.button_add)
    Button mButtonAdd;
    @InjectView(R.id.txtview_hostname)
    TextView mTxtviewHostname;
    private Context mContext;
    private ProfilesManager mProfilesManager;

    private QrCodeModal mCurrentQr;
    private RepositoryProfile mCurrentProfile;
    private String mQrSessionId;
    private String mPublicKey;
    private String mRuntime_key;
    private String mHostname;
    private String mPathname;

    private String mQrId;
    private String mSid;

    /**
     * 判断来源于singou 还是 teleform
     */
    private int mSource;

    private List<Profile> mProfileList;
    private MultiLoginUserAdapter mMultiLoginUserAdapter;
    private Bundle mBundle;

    @OnClick(R.id.button_add)
    void add() {
        Intent intent = getIntent();
        intent.setClass(this, InputUserInfoActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.btn_cancel)
    void backClick() {
        finish();
    }

    @OnItemClick(R.id.user_list)
    void itemClick(int position){
        Profile profile = mProfileList.get(position);
        try {
            if(isFromSingou()) {
                SingouManager.getInstance().sendAuth(mSid, profile.getUsername(), profile.getPassword(), mQrId, mRuntime_key);
            }
            else {
                TeleformManager.getInstance().updateSession(mQrSessionId, profile.getUsername(), profile.getPassword(), mPublicKey, mRuntime_key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multi_info_activity);
        ButterKnife.inject(this);

        mContext = MultiUserInfoActivity.this;
        mProfilesManager = ProfilesManager.getInstance();

        mSource = getIntent().getIntExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, -1);

        mBundle = getIntent().getBundleExtra(CaptureFragment.EXTRA_QRCODE_RESULT);
        if (!isFromSingou()) {
            mQrSessionId = mBundle.getString(CaptureFragment.BUNDLE_KEY_SESSIONID);
            mRuntime_key = mBundle.getString(CaptureFragment.BUNDLE_KEY_RUNTIME_KEY);
            mPublicKey = mBundle.getString(CaptureFragment.BUNDLE_KEY_PUBKEY);
            mPathname = mBundle.getString(CaptureFragment.BUNDLE_PATH_NAME);
            mHostname = mBundle.getString(CaptureFragment.BUNDLE_KEY_URL);
            mTxtviewHostname.setText(mHostname);
        } else {
            mCurrentQr = (QrCodeModal) mBundle.getSerializable(CaptureFragment.BUNDLE_KEY_QR);
            mQrId = mCurrentQr.getI();
            mSid = mBundle.getString(CaptureFragment.BUNDLE_KEY_SID);
            mRuntime_key = mBundle.getString(CaptureFragment.BUNDLE_KEY_RUNTIME_KEY);
            mCurrentProfile = mCurrentQr.getProfile();
            mHostname = mCurrentProfile.getTitle();

            if (null != mCurrentProfile)
                mTxtviewHostname.setText(mHostname);
        }

        mProfileList = mProfilesManager.getProfilesByTarget(mSource, mHostname);
        mMultiLoginUserAdapter = new MultiLoginUserAdapter(mContext, mProfileList);
        mUserList.setAdapter(mMultiLoginUserAdapter);
    }


    @Override
    public IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UpdateSessionTask.ACTION_UPDATE_SESSION_TASK);
        intentFilter.addAction(SendAuthTask.ACTION_SEND_AUTH_TASK);
        return intentFilter;
    }

    @Override
    public void handleOnReceive(Intent intent) {
        String action = intent.getAction();
        if (UpdateSessionTask.ACTION_UPDATE_SESSION_TASK.equals(action)) {
            handleUpdateSession(intent);
        } else if (SendAuthTask.ACTION_SEND_AUTH_TASK.equals(action)) {
            handleSendAuth(intent);
        }

    }

    private void handleUpdateSession(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                ShortSoundUtil.getInstance().unlock();
                ToastUtil.showMessageInShort(context, R.string.login_success);
                finish();
                break;
            case TaskController.EVENT_TASK_FAILED:
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                break;
            case TaskController.EVENT_TASK_ERROR:

                break;
            default:
                break;
        }
    }

    private void handleSendAuth(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                finish();
                ShortSoundUtil.getInstance().unlock();
                ToastUtil.showMessageInShort(mContext, R.string.auth_success);
                break;
            case TaskController.EVENT_TASK_FAILED:

                break;
            case TaskController.EVENT_TASK_ERROR:
                finish();
                ToastUtil.showMessageInShort(mContext, R.string.auth_fail);
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
//        this.overridePendingTransition(R.anim.activity_close,0);
    }

    private boolean isFromSingou() {
        return Constants.SOURCE_SINGOU == mSource;
    }


}